package com.ruoyi.order.file;

import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * API Key拦截器
 */
public class ApiKeyInterceptor implements HandlerInterceptor {

    private static final String API_KEY_HEADER = "X-API-KEY";
    private static final String VALID_API_KEY = "RuoYi2023";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 从header中获取API Key
        String apiKey = request.getHeader(API_KEY_HEADER);

        if (apiKey == null || apiKey.isEmpty()) {
            ServletUtils.renderString(response, AjaxResult.error("缺少API Key").toString());
            return false;
        }

        if (!VALID_API_KEY.equals(apiKey)) {
            ServletUtils.renderString(response, AjaxResult.error("无效的API Key").toString());
            return false;
        }

        return true;
    }
}